package com.easylinkin.linkappapi.childinspection.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.childinspection.entity.InspectionPointEntity;
import com.easylinkin.linkappapi.childinspection.entity.InspectionTaskEntity;
import com.easylinkin.linkappapi.childinspection.mapper.InspectionMapper;
import com.easylinkin.linkappapi.childinspection.mapper.InspectionPointMapper;
import com.easylinkin.linkappapi.childinspection.service.InspectionService;
import com.easylinkin.linkappapi.childinspection.vo.BaseVo;
import com.easylinkin.linkappapi.childinspection.vo.InspectionPersonVo;
import com.easylinkin.linkappapi.childinspection.vo.InspectionTaskVo;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.security.mapper.LinkappUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author linWenLe
 * @Date: 2024/3/27
 * @Description:
 */
@Slf4j
@Service("inspectionService")
public class InspectionServiceImpl extends ServiceImpl<InspectionMapper, InspectionTaskEntity> implements InspectionService {

    @Resource
    LinkappUserContextProducer linkappUserContextProducer;

    @Resource
    private InspectionMapper inspectionMapper;

    @Resource
    private LinkappUserMapper linkappUserMapper;


    @Resource
    private InspectionPointMapper inspectionPointMapper;

    @Override
    public IPage<InspectionTaskEntity> getTaskList(RequestModel<InspectionTaskVo> restPage) {
        Page page = restPage.getPage();
        return inspectionMapper.getTaskList(page, restPage.getCustomQueryParams());
    }

    @Override
    @Transactional
    public void insert(InspectionTaskVo entityVo) {
        Assert.notNull(entityVo.getInspectionName(), "巡检任务名称不能为空");
        LambdaQueryWrapper<InspectionTaskEntity> floorWrapper = Wrappers.lambdaQuery();
        List<InspectionTaskEntity> codeList = inspectionMapper.selectList(floorWrapper.eq(InspectionTaskEntity::getInspectionName, entityVo.getInspectionName()));
        Assert.isTrue(codeList.size() == 0, "巡检任务名称已存在");
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        InspectionTaskEntity entity = new InspectionTaskEntity();
        BeanUtils.copyProperties(entityVo,entity);
        String uuid = UUID.randomUUID().toString();
        entity.setId(uuid);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            entity.setStartTime(format.parse(entityVo.getStartTime()));
            entity.setEndTime(format.parse(entityVo.getEndTime()));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        entity.setCreateTime(new Date());
        entity.setCreator(tenantId);
        entity.setTenantId(tenantId);
        List<InspectionPointEntity> pointList = entityVo.getPointList();
        entity.setInspectionPoint(pointList.size());
        inspectionMapper.insert(entity);
        //添加关联表
        for (InspectionPointEntity point : pointList) {
            inspectionMapper.insertTaskAndPoint(uuid, point.getId());
        }
    }

    @Override
    @Transactional
    public void update(InspectionTaskEntity entity) {
        entity.setModifyTime(new Date());
        entity.setModifier(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        List<InspectionPointEntity> pointList = entity.getPointList();
        entity.setInspectionPoint(pointList.size());
        //删除关联巡检点再新增
        inspectionMapper.deleteTaskAndPointByTaskId(entity.getId());
        for (InspectionPointEntity point : pointList) {
            inspectionMapper.insertTaskAndPoint(entity.getId(), point.getId());
        }
        inspectionMapper.updateById(entity);
    }

    @Override
    @Transactional
    public void delete(String id) {
        int count = inspectionMapper.selectListByTaskId(id);
        Assert.isTrue(count == 0, "存在当日巡检任务，不能删除");
        inspectionMapper.deleteTaskAndPointByTaskId(id);
        inspectionMapper.deleteById(id);
    }


    @Override
    public List<LinkappUser> getPersonList(InspectionPersonVo vo) {
        QueryWrapper<LinkappUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("tenant_id",linkappUserContextProducer.getNotNullCurrent().getTenantId());
        if (vo.getName() != null){
            userQueryWrapper.like("nickname",vo.getName());
        }
        return linkappUserMapper.selectList(userQueryWrapper);
    }


    @Override
    public InspectionTaskEntity getTaskInfo(String id) {
        InspectionTaskEntity taskEntity = inspectionMapper.selectById(id);
        List<InspectionPointEntity> list = inspectionPointMapper.selectPointList(id);
        taskEntity.setPointList(list);
        return taskEntity;
    }

    @Override
    public IPage<InspectionPointEntity> getTodayTaskInfo(RequestModel<BaseVo> restPage) {
        Page page = restPage.getPage();
        return inspectionPointMapper.getTodayTaskInfo(page, restPage.getCustomQueryParams());
    }

    @Override
    public Map<String, Object> getAppTaskInfo(String id) {
        InspectionTaskEntity taskEntity = inspectionMapper.selectById(id);
        String taskId = taskEntity.getId();
        List<InspectionPointEntity> point = inspectionPointMapper.selectPointList(taskId);
        Map<String, Object> map = new HashMap<>();
        map.put("list", point);
        long count = point.stream().filter(e -> e.getStatus() == 1).count();
        map.put("id", taskId);
        map.put("name", taskEntity.getInspectionName());
        map.put("count", count + "/" + taskEntity.getInspectionPoint());
        map.put("status", count == taskEntity.getInspectionPoint() ? "已完成": "进行中");
        return map;
    }


    @Override
    public List<Map<String, Object>> getAppTaskList() {
        LambdaQueryWrapper<InspectionTaskEntity> wrapper = Wrappers.lambdaQuery();
        List<InspectionTaskEntity> taskEntities = inspectionMapper.selectList(wrapper.like(InspectionTaskEntity::getCreateTime, DateUtil.format(new Date(), "yyyy-MM-dd")));
        List<Map<String, Object>> list = new ArrayList<>();
        for (InspectionTaskEntity taskEntity : taskEntities) {
            Map<String, Object> map = new HashMap<>();
            List<InspectionPointEntity> point = inspectionPointMapper.selectPointList(taskEntity.getId());
            map.put("list", point);
            long count = point.stream().filter(e -> e.getStatus() == 1).count();
            map.put("id", taskEntity.getId());
            map.put("name", taskEntity.getInspectionName());
            map.put("count", count + "/" + taskEntity.getInspectionPoint());
            map.put("status", count == taskEntity.getInspectionPoint() ? "已完成": "进行中");
            list.add(map);
        }
        return list;
    }

    @Override
    public IPage<Map<String, Object>> getHistoryTaskList(RequestModel<BaseVo> restPage) {
        Page page = restPage.getPage();
        IPage<InspectionTaskEntity> taskInfo = inspectionMapper.getHistoryTaskList(page, restPage.getCustomQueryParams());
        List<InspectionTaskEntity> taskEntities = taskInfo.getRecords();
        List<Map<String, Object>> list = new ArrayList<>();
        for (InspectionTaskEntity taskEntity : taskEntities) {
            Map<String, Object> map = new HashMap<>();
            List<InspectionPointEntity> point = inspectionPointMapper.selectPointList(taskEntity.getId());
            map.put("list", point);
            long count = point.stream().filter(e -> e.getStatus() == 1).count();

            map.put("id", taskEntity.getId());
            map.put("name", taskEntity.getInspectionName());
            map.put("count", count + "/" + taskEntity.getInspectionPoint());
            map.put("status", count == taskEntity.getInspectionPoint() ? "已完成": "超时未完成");
            list.add(map);
        }
        IPage<Map<String, Object>> result = new Page<>();
        BeanUtils.copyProperties(taskInfo,result);
        result.setRecords(list);
        return result;
    }
}
